import router from "@/router";
import axios from 'axios';
import {Loading, Message} from "element-ui";
import { saveAs } from 'file-saver'
import errorCode from "@/utils/errorCode";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

let downloadLoadingInstance;

// 使用request发请求
const request = axios.create({
    baseURL:  '/api', // 后端的接口地址 ip:port
    timeout: 30 * 1000, //在30秒内返回，否则报错
});

// request拦截前
// 可以在请求发送前对请求做一些处理
// 比如统一加上token，对请求参数统一加密

request.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8'
    let user = JSON.parse(sessionStorage.getItem('user-key') || '{}')
    config.headers['token'] = user?.token // 设置请求头

    return config
}, error => {
    return Promise.reject(error)
})

// response 拦截器
// 可以在接口响应后统一处理结果
// 响应的统一设置
request.interceptors.response.use(response => {
        let res = response.data
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        if (res.code === '401') {
            router.push('/login').then(res => {
                this.$message.error(res.msg)
            })
        }
        return res
    }, error => {
        return Promise.reject(error)
    }
)

// 通用下载方法
export function download(url, params, filename, config) {
    downloadLoadingInstance = Loading.service({ text: "正在下载数据，请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
    return request.post(url, params, {
        transformRequest: [(params) => { return tansParams(params) }],
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        responseType: 'blob',
        ...config
    }).then(async (data) => {
        const isBlob = blobValidate(data);
        if (isBlob) {
            const blob = new Blob([data])
            saveAs(blob, filename)
        } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
            Message.error(errMsg);
        }
        downloadLoadingInstance.close();
    }).catch((r) => {
        console.error(r)
        Message.error('下载文件出现错误，请联系管理员！')
        downloadLoadingInstance.close();
    })
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

// 验证是否为blob格式
export function blobValidate(data) {
    return data.type !== 'application/json'
}

export default request
